package com.duobaoyu.dby.supply.biz.strategy.export;

import com.alibaba.fastjson.JSON;
import com.duobaoyu.dby.channel.adapter.enums.ChannelCodeEnum;
import com.duobaoyu.dby.channel.adapter.enums.biz.order.OrderStatusEnum;
import com.duobaoyu.dby.channel.adapter.enums.biz.product.InsideStatusEnum;
import com.duobaoyu.dby.channel.adapter.enums.biz.product.ProductTypeEnum;
import com.duobaoyu.dby.common.core.constant.StringPool;
import com.duobaoyu.dby.common.core.util.StringUtil;
import com.duobaoyu.dby.common.mybatis.util.EnumUtils;
import com.duobaoyu.dby.saas.product.common.base.json.SaleAttribute;
import com.duobaoyu.dby.supply.biz.client.resource.ResourceApiClient;
import com.duobaoyu.dby.supply.biz.client.resource.bean.bo.BusinessConfigBO;
import com.duobaoyu.dby.supply.biz.converter.OrderConverter;
import com.duobaoyu.dby.supply.biz.converter.PreWarningConfigConverter;
import com.duobaoyu.dby.supply.common.biz.bo.order.OrderExportBO;
import com.duobaoyu.dby.supply.common.biz.dto.config.PreWarningConditionDTO;
import com.duobaoyu.dby.supply.common.biz.dto.order.OrderPageDTO;
import com.duobaoyu.dby.supply.common.biz.excel.OrderExportData;
import com.duobaoyu.dby.supply.core.task.bean.TaskAsyncParam;
import com.duobaoyu.dby.supply.core.task.bean.exporttask.TaskExport;
import com.duobaoyu.dby.supply.core.task.enums.BizTaskTypeEnum;
import com.duobaoyu.dby.supply.core.task.strategy.AbstractExportAsyncStrategy;
import com.duobaoyu.dby.supply.db.entity.config.PreWarningConfig;
import com.duobaoyu.dby.supply.db.repository.config.PreWarningConfigRepository;
import com.duobaoyu.dby.supply.db.repository.order.OrderRepository;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * 订单列表导出策略
 * @Author yangyong
 * @Date 2023/10/20
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class OrderExportStrategy extends AbstractExportAsyncStrategy<OrderExportData> {
	private final OrderConverter orderConverter;
	private final OrderRepository orderRepository;
	private final ResourceApiClient resourceApiClient;
	private final PreWarningConfigConverter preWarningConfigConverter;
	private final PreWarningConfigRepository preWarningConfigRepository;
	private static final List<Integer> ORDER_STATUS_LIST = Arrays.asList(OrderStatusEnum.WAIT_PAY.getValue(), OrderStatusEnum.CANCEL.getValue());

	@Override
	protected String bizTaskType() {
		return BizTaskTypeEnum.SUPPLY_CHAIN_PURCHASE_ORDER.getValue();
	}

	@Override
	protected TaskAsyncParam beforeHandler(TaskAsyncParam taskAsyncParam) {
		String param = taskAsyncParam.getTaskParam();
		TaskExport taskExport = JSON.parseObject(param, TaskExport.class);
		String searchParameter = taskExport.getSearchParameter();
		OrderPageDTO orderPage = JSON.parseObject(searchParameter, OrderPageDTO.class);
		if(Objects.nonNull(orderPage.getPreWarningStrategyId())){
			PreWarningConfig preWarningConfig = preWarningConfigRepository.getById(orderPage.getPreWarningStrategyId());
			PreWarningConditionDTO preWarningCondition = preWarningConfigConverter.parsePreWarningCondition(preWarningConfig);
			if(Objects.nonNull(preWarningCondition)){
				orderPage.setPreWarningCondition(preWarningCondition);
				taskExport.setSearchParameter(JSON.toJSONString(orderPage));
				taskAsyncParam.setTaskParam(JSON.toJSONString(taskExport));
			}
		}
		return taskAsyncParam;
	}

	@Override
	protected List<OrderExportData> dataSourcePage(String param, Integer pageSize, Integer pageNo){
		OrderPageDTO orderPage = JSON.parseObject(param, OrderPageDTO.class);
		List<OrderExportBO> orderExportList = orderRepository.listOrderExportInfo(orderPage);
		return this.buildOrderExportData(orderExportList);
	}

	@Override
	protected long dataTotalCount(String param) {
		OrderPageDTO orderPage = JSON.parseObject(param, OrderPageDTO.class);
		return orderRepository.countOrderExportInfo(orderPage);
	}

	/**
	 * 组装订单列表导出信息
	 */
	private List<OrderExportData> buildOrderExportData(List<OrderExportBO> orderExportList){
		List<OrderExportData> exportDataList = Lists.newArrayList();
		if(CollectionUtils.isEmpty(orderExportList)){
			return exportDataList;
		}
		for(OrderExportBO orderExport : orderExportList){
			OrderExportData exportData = orderConverter.toOrderExport(orderExport);
			//供应渠道
			ChannelCodeEnum channelCodeEnum = ChannelCodeEnum.getChannelCodeEnumByCode(orderExport.getChannelCode());
			if(Objects.nonNull(channelCodeEnum)){
				exportData.setChannelDesc(channelCodeEnum.getDescribe());
			}
			//订单来源
			if(StringUtil.isNotBlank(orderExport.getServerName())){
				BusinessConfigBO bizConfig = resourceApiClient.getBizCodeInfo(orderExport.getServerName());
				if(Objects.nonNull(bizConfig)){
					exportData.setServerName(bizConfig.getBizDescribe());
				}
			}
			//运费、订单总计、实付款
			BigDecimal freightAmount = BigDecimal.ZERO;
			BigDecimal payAmount = orderExport.getPlatformSellPrice().multiply(new BigDecimal(orderExport.getSkuNum()));
			BigDecimal orderTotalAmount = orderExport.getPlatformSellPrice().multiply(new BigDecimal(orderExport.getSkuNum()));

			if(Objects.nonNull(orderExport.getChannelFreightAmount())){
				freightAmount = orderExport.getChannelFreightAmount();
				orderTotalAmount = payAmount.add(freightAmount);
			}
			//已取消|待支付状态的订单,实付款金额展示为0
			if(ORDER_STATUS_LIST.contains(orderExport.getOrderStatus())){
				payAmount = BigDecimal.ZERO;
			}else{
				payAmount = payAmount.add(freightAmount);
			}
			exportData.setFreightAmount(freightAmount.toString());
			exportData.setOrderTotalAmount(orderTotalAmount);
			exportData.setPayAmount(payAmount);
			//商品规格
			if(CollectionUtils.isNotEmpty(orderExport.getSaleAttributes())){
				List<SaleAttribute> saleAttributes = orderExport.getSaleAttributes();
				saleAttributes.sort(Comparator.comparing(SaleAttribute::getSort));
				StringBuilder value = new StringBuilder();
				for(SaleAttribute saleAttribute : saleAttributes){
					value.append(saleAttribute.getValue());
					value.append(StringPool.ASTERISK);
				}
				if(value.length() > 0){
					value.deleteCharAt(value.length() - 1);
				}
				exportData.setSaleAttributes(String.valueOf(value));
			}

			//订单状态
			OrderStatusEnum orderStatusEnum = OrderStatusEnum.getOrderSubStatusEnum(orderExport.getOrderStatus());
			if(Objects.nonNull(orderStatusEnum)){
				exportData.setOrderStatusDesc(orderStatusEnum.getDescribe());
				if(EnumUtils.eq(OrderStatusEnum.COMPLETE,orderStatusEnum.getValue())) {
					exportData.setCancelReason(StringPool.EMPTY);
				}
			}
			ProductTypeEnum productTypeEnum = ProductTypeEnum.getProductTypeEnum(orderExport.getProductType());
			if(Objects.nonNull(productTypeEnum)){
				exportData.setProductType(productTypeEnum.getDescribe());
			}
			if(Objects.nonNull(orderExport.getInsideStatus())){
				InsideStatusEnum insideStatusEnum = InsideStatusEnum.getInsideStatus(orderExport.getInsideStatus());
				if(Objects.nonNull(insideStatusEnum)){
					exportData.setInsideStatus(insideStatusEnum.getDescribe());
				}
			}
			//业务来源
			if(StringUtils.isNotBlank(orderExport.getShowServerName())){
				BusinessConfigBO bizConfig = resourceApiClient.getBizCodeInfo(orderExport.getShowServerName());
				if(Objects.nonNull(bizConfig)){
					exportData.setShowServerName(bizConfig.getBizDescribe());
				}
			}
			exportDataList.add(exportData);
		}
		return exportDataList;
	}
}